SpringMVC框架(5) —— 文件上传

项目结构(文件服务器)

  • webapp
    • uploads(图片存储位置)
    • WEB-INF
      • pages
        • success.jsp(web页面)
      • web.xml(web配置文件)
    • index.jsp(web页面)
  • pom.xml(maven项目配置文件)

项目结构(应用服务器)

  • java
    • controller
      • FileUploadController.java(Java文件)
  • resources
    • springmvc.xml(springmvc配置文件)
  • webapp
    • WEB-INF
      • pages
        • success.jsp(web页面)
      • web.xml(web配置文件)
    • index.jsp(web页面)
  • pom.xml(maven项目配置文件)

maven项目配置文件

  • 配置maven项目需要的依赖
    • spring-context
    • spring-web
    • spring-webmvc
    • servlet-api
    • jsp-api
    • commons-fileupload
    • commons-io
    • jersey-core
    • jersey-client

web配置文件

  • 前端控制器(DispatcherServlet)
    • 配置一个前端控制器(<servlet>)
      • 创建前端控制器时,加载Spring配置文件(<init-param>)
      • 启动服务器时,创建前端控制器(<\load-on-startup>)
    • 配置前端控制器的作用范围(<servlet-mapping>)
  • 过滤器(CharacterEncodingFilter)
    • 配置一个过滤器(<filter>)
      • 配置编码(<init-param>):解决中文乱码
    • 配置前端控制器的作用范围(<filter-mapping>)

springmvc配置文件

  • 导入名称空间(<beans xmlns=””>)
  • 开启注解扫描(<context:component-scan base-package=””>)
  • 配置视图解析器(InternalResourceViewResolver)
    • 配置前缀(prefix -> “/WEB-INF/pages”)
    • 配置后缀(suffix -> “.jsp”)
  • 开启SpringMVC注解支持(<mvc:annotation-driven>)

Java文件

  • 表现层
      • 添加进IoC核心容器(@Controller)
      • 设置请求映射(@RequestMapping())
        • 一级目录(path=””)
    • 方法
      • 设置请求映射(@RequestMapping())
        • 二级目录(path=””)
      • 返回值(return “success”;)
      • 参数列表(数据类型 请求参数名,数据类型 请求参数名)
        • HttpServletRequest
        • MultipartFile

JSP文件

  • 超链接(href=”一级目录/二级目录?请求参数=值&请求参数=值”)
  • 表单(<form action=”一级目录/二级目录” method=”post”>)

执行代码

  • 需求:通过服务器将图片上传至服务器端

  • 在“应用服务器”中,上传图片。图片通过跨服务器操作,被存储到“文件服务器”中。

    “文件服务器”只需要新建一个模板,并且配置一个tomcat服务器,在此需求中其配置文件不需要设置。

pom.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>cn.water</groupId>
<artifactId>section03_FileUpload</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<name>section03_FileUpload Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>

<!-- 版本锁定 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.0.2.RELEASE</spring.version>
</properties>

<!-- 依赖注入 -->
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- jsp -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<!-- 解析请求正文内容(Form表单的enctype属性取值为Mutilpart/form-date时) -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<!-- 跨服务器上传 -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18.1</version>
</dependency>

</dependencies>


<build>
<finalName>section03_FileUpload</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
<display-name>Archetype Created Web Application</display-name>

<!-- 【filter】 -->
<filter>
<!-- 创建过滤器 -->
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!-- 配置编码 -->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<!-- 映射 -->
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- 【servlet】 -->
<servlet>
<!-- 创建DispatcherServlet -->
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 创建DispatcherServlet时,加载spring配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- 启动服务器时,创建DispatcherServlet -->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 映射 -->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>




</web-app>

springmvc.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">


<!-- 开启注解扫描 -->
<context:component-scan base-package="cn.water"/>


<!-- 视图解析器 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<!-- 配置前缀 -->
<property name="prefix" value="/WEB-INF/pages/"></property>
<!-- 配置后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>

<!-- 文件解析器 -->
<!-- 此id必须为multipartResolver -->
<!-- 配置了文件解析器后,通过commons-fileupload组件的方法可以访问,无法上传。 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 配置上传文件字节数的最大值 -->
<property name="maxUploadSize" value="10485760"></property>
</bean>

<!-- 开启springMVC框架注解支持 -->
<mvc:annotation-driven/>


</beans>

FileUploadController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package cn.water.controller;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.UUID;


@Controller
@RequestMapping("/fileUpload")
public class FileUploadController {


/* 传统方式:通过 commons-fileupload组件 解析消息正文 */
@RequestMapping("/test01")
public String testFileUpload(HttpServletRequest request,String picname) throws Exception {
/* 设置 文件上传的位置 */
String realPath = request.getSession().getServletContext().getRealPath("/uploads/");
System.out.println(realPath);
/* 创建 文件夹 */
File file = new File(realPath);
if (!file.exists()){
file.mkdirs();
}
/* 解析消息正文,获取上传文件项 */
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> fileItems = upload.parseRequest(request);
/* 判断是否为上传文件项 */
for (FileItem fileItem : fileItems) {
if (fileItem.isFormField()){
/* 表单项 */
}else {
/* 上传文件项 */
/* 设置唯一的文件名称 */
String name = fileItem.getName();
String uuid = UUID.randomUUID().toString().replace("-", "");
name = uuid +"_"+ picname +"_"+ name; // 唯一标识码 + 输入的名称 + 文件本身名称
System.out.println(name);
/* 在指定位置创建文件 */
fileItem.write(new File(realPath,name));
/* 删除临时文件 */
fileItem.delete();
}
}
return "success";
}


/* SpringMVC传统方法:文件解析器来解析,我们只需要获取 MultipartFile对象 */
@RequestMapping("/test02")
public String test02( HttpServletRequest request, MultipartFile picture,String picname) throws Exception {
/* 设置 文件上传的位置 */
String realPath = request.getSession().getServletContext().getRealPath("/uploads/");
System.out.println(realPath);
/* 创建 文件夹 */
File file = new File(realPath);
if (!file.exists()){
file.mkdirs();
}
/* 设置唯一的文件名称 */
String name = picture.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replace("-", "");
name = uuid +"_"+ picname +"_"+ name; // 唯一标识码 + 输入的名称 + 文件本身名称
System.out.println(name);
/* 在指定位置创建文件 */
picture.transferTo(new File(file,name));
return "success";
}


/* SpringMVC跨服务器上传 */
@RequestMapping("/test03")
public String test03(MultipartFile picture,String picname) throws Exception {

/* 定义上传文件服务器的路径 */
String path = "http://localhost:9090/uploads/";

/* 设置唯一的文件名称 */
System.out.println(picture);
String name = picture.getOriginalFilename();
// String uuid = UUID.randomUUID().toString().replace("-", "");
// name = uuid +"_"+ picname +"_"+ name; // 唯一标识码 + 输入的名称 + 文件本身名称
System.out.println(path);
System.out.println(name);

/* 创建客服端对象 */
Client client = Client.create();
/* 和图片服务器进行连接 */
WebResource resource = client.resource(path + name);
/* 上传文件 */
resource.put(picture.getBytes());


return "success";
}




}

index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>文件上传</h1>
<hr>

<h2>传统方式:通过 commons-fileupload组件</h2>
<form action="fileUpload/test01" method="post" enctype="multipart/form-data">
名称:<input type="text" name="picname"> <br>
选择图片:<input type="file" name="picture"> <br>
<input type="submit" value="上传文件">
</form>
<hr>

<h2>SpringMVC传统方法:文件解析器</h2>
<form action="fileUpload/test02" method="post" enctype="multipart/form-data">
名称:<input type="text" name="picname"> <br>
选择图片:<input type="file" name="picture"> <br> <%-- 和Controller中方法的MultipartFile参数的名称必须一致 --%>
<input type="submit" value="上传文件">
</form>
<hr>

<h2>SpringMVC跨服务器方法</h2>
<form action="fileUpload/test03" method="post" enctype="multipart/form-data">
名称:<input type="text" name="picname"> <br>
选择图片:<input type="file" name="picture"> <br> <%-- 和Controller中方法的MultipartFile参数的名称必须一致 --%>
<input type="submit" value="上传文件">
</form>
<hr>




</body>
</html>

success.jsp

1
2
3
4
5
6
7
8
9
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>访问成功!!!</h1>
</body>
</html>

传统方式

  • 传统的文件上传方式通过 commons-fileupload组件
  • maven配置文件
1
2
3
4
5
6
7
8
9
10
<!-- 解析请求正文内容(Form表单的enctype属性取值为Mutilpart/form-date时) -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
  • Controller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@RequestMapping("/test01")
public String testFileUpload(HttpServletRequest request,String picname) throws Exception {
/* 设置 文件上传的位置 */
String realPath = request.getSession().getServletContext().getRealPath("/uploads/");
System.out.println(realPath);
/* 创建 文件夹 */
File file = new File(realPath);
if (!file.exists()){
file.mkdirs();
}
/* 解析消息正文,获取上传文件项 */
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> fileItems = upload.parseRequest(request);
/* 判断是否为上传文件项 */
for (FileItem fileItem : fileItems) {
if (fileItem.isFormField()){
/* 表单项 */
}else {
/* 上传文件项 */
/* 设置唯一的文件名称 */
String name = fileItem.getName();
String uuid = UUID.randomUUID().toString().replace("-", "");
name = uuid +"_"+ picname +"_"+ name; // 唯一标识码 + 输入的名称 + 文件本身名称
System.out.println(name);
/* 在指定位置创建文件 */
fileItem.write(new File(realPath,name));
/* 删除临时文件 */
fileItem.delete();
}
}
return "success";
}

SpringMVC方式

  • 文件解析器来解析,我们只需要获取 MultipartFile对象
  • SpringMVC配置文件
1
2
3
4
5
6
7
<!-- 文件解析器 -->
<!-- 此id必须为multipartResolver -->
<!-- 配置了文件解析器后,通过commons-fileupload组件的方法可以访问,无法上传。 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 配置上传文件字节数的最大值 -->
<property name="maxUploadSize" value="10485760"></property>
</bean>
  • Controller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@RequestMapping("/test02")
public String test02( HttpServletRequest request, MultipartFile picture,String picname) throws Exception {
/* 设置 文件上传的位置 */
String realPath = request.getSession().getServletContext().getRealPath("/uploads/");
System.out.println(realPath);
/* 创建 文件夹 */
File file = new File(realPath);
if (!file.exists()){
file.mkdirs();
}
/* 设置唯一的文件名称 */
String name = picture.getOriginalFilename();
String uuid = UUID.randomUUID().toString().replace("-", "");
name = uuid +"_"+ picname +"_"+ name; // 唯一标识码 + 输入的名称 + 文件本身名称
System.out.println(name);
/* 在指定位置创建文件 */
picture.transferTo(new File(file,name));
return "success";
}

跨服务器上传

  • Maven配置文件
1
2
3
4
5
6
7
8
9
10
<!-- 解析请求正文内容(Form表单的enctype属性取值为Mutilpart/form-date时) -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
  • SpringMVC配置文件
1
2
3
4
5
6
7
8
9
10
11
<!-- 跨服务器上传 -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.18.1</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.18.1</version>
</dependency>
  • Controller
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 @RequestMapping("/test03")
public String test03(MultipartFile picture,String picname) throws Exception {

/* 定义上传文件服务器的路径 */
String path = "http://localhost:9090/uploads/";

/* 设置唯一的文件名称 */
System.out.println(picture);
String name = picture.getOriginalFilename();
// String uuid = UUID.randomUUID().toString().replace("-", "");
// name = uuid +"_"+ picname +"_"+ name; // 唯一标识码 + 输入的名称 + 文件本身名称
System.out.println(path);
System.out.println(name);

/* 创建客服端对象 */
Client client = Client.create();
/* 和图片服务器进行连接 */
WebResource resource = client.resource(path + name);
/* 上传文件 */
resource.put(picture.getBytes());

return "success";
}
  • tomcat配置文件 (D:\coding\Tomcat\apache-tomcat-8.5.45\conf\web.xml)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    <servlet>
    <servlet-name>default</servlet-name>
    <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
    <init-param>
    <param-name>debug</param-name>
    <param-value>0</param-value>
    </init-param>
    <init-param>
    <param-name>listings</param-name>
    <param-value>false</param-value>
    </init-param>
    <init-param>
    <param-name>readonly</param-name>
    <param-value>false</param-value>
    </init-param>

    <load-on-startup>1</load-on-startup>
    </servlet>
-------------本文结束-------------
Donate comment here